<!--
批量剔除界面：用户选择了指定的年份和负责部门后，点击“批量剔除”按钮进入此界面，在此界面中直接搜索某些可能剔除的奖金记录，跨人员执行剔除操作
-->
<template>
  <div class="mod-config">
    <basic-container>
      <div v-if="ymLoad" class="duiQitishi">
        <div class="tiShiTu">
          <img src="/images/qita/tishi.png" width="300">
        </div>
        <div class="tiShi">
          <div><b>您现在不是任何部门的奖金管理人员，无法进行奖金剔除操作</b></div>
          <div class="font18 mt10">您可以通知系统管理员，为您设置具体的奖金管理部门！</div>
        </div>
      </div>
      <div class="boxsty zhiBiao" v-else>
        <div class="flex justifyContentSpaceBetween">
          <div class="tabletext">统计已发奖金</div>
        </div>
        <div class="colForm">
          <el-form
            :inline="true"
            class="form-inline"
            label-width="80px"
            style="margin-bottom: 0px"
          >
            <el-form-item label="年份">
              <el-date-picker
                :clearable="false"
                v-model="searchParam.years"
                format="yyyy" value-format="yyyy"
                @change="yearsChangeHandle"
                type="year"
                placeholder="选择年">
              </el-date-picker>
            </el-form-item>
            <div label="处理部门" v-show="false">
              <el-select v-model="searchParam.rootDeptCode" placeholder="请选择负责部门" class="xiaLa mr20"
                         @change="deptCodeChangeHandle">
                <el-option v-for="item in bmData" :key="item.deptCode" :label="item.deptName"
                           :value="item.deptCode"></el-option>
              </el-select>
            </div>
            <el-form-item label="数据来源">
              <el-select v-model="searchParam.sourceType" class="xiaLa mr20" @change="sourceTypeChangeHandle">
                <el-option label="ECC统计奖金" value="1"></el-option>
                <el-option label="绩效统计奖金" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职级">
              <!--@change="ryZjbmsChangeHandleWithAutoSave"        -->
              <el-select :clearable="true" v-model="searchParam.ryZjbms" placeholder="请选择" class="xiaLa"
                         :automaticDropdown="ryZjbmsSelectAutoDropdown" ref="ryZjbmsSelectRef"
                         :disabled="ryZjbmsSelectDisabled" v-loading="ryZjbmsSelectDisabled"
                         :collapse-tags="true" multiple :style="'width: ' + ryZjbmsIfChange?'80%':'100%'">
                <el-option v-for="item in ryZjbmOptions " :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-button
                v-show='ryZjbmsIfChange'
                size="mini" type="warning" @click="ryZjbmsUpdateHandle"
                icon="el-icon-check" title="点击将当前操作职级改动修改生效" circle></el-button>
            </el-form-item>
            <el-form-item label="已获取日期" label-width="100px">
              <el-input v-model="importDate" disabled/>
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="warning"
                class="marginLeft"
                :disabled="searchParam.rootDeptCode===''"
                @click="importDataFromInterface"
                v-loading="importLoading"
              >获取数据
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider></el-divider>
        <div :height="searchheight">
          <span
            style="float: right; cursor: pointer"
            @click="searchAdvancedChangeHandle"
          >{{ searchAdvanced ? "查询条件收起" : "查询条件展开" }}
            <i
              :class="
                searchAdvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "
            />
          </span>
          <!--    可展开搜索区      -->
          <div v-show="searchAdvanced" class="colForm">
            <el-form
              :inline="true"
              @keyup.enter.native="getDataList()"
              class="form-inline"
              label-width="100px"
            >
              <el-col :span="6">
                <el-form-item label="人员姓名">
                  <el-input v-model="searchParam.ryName" clearable style="width: 200px"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人员编号">
                  <el-input v-model="searchParam.ryCode" clearable style="width: 200px"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工作单位">
                  <deptAvueInputTree ref="searchDeptTree" v-model="searchParam.deptCode"
                                    @returnDeptCode="returnDeptCodeFromAvueInputTree"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="ECC奖金分类" label-width="110px">
                  <el-select clearable v-model="searchParam.jjxFl" placeholder="请选择" class="xiaLa"
                            style="width: 200px">
                    <el-option v-for="item in jjflOptions " :key="item.label" :label="item.label" :value="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="奖金项" v-if="searchParam.sourceType==2">
                  <el-select clearable v-model="searchParam.jjxMc" placeholder="请选择" class="xiaLa"
                            style="width: 200px">
                    <el-option v-for="item in jjxMcOptions " :key="item" :label="item"
                              :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!--  人员职级编码 允许多选            -->
              <el-col :span="6">
                <el-form-item label="检索职级">
                  <el-select :clearable="true" v-model="searchParam.ryZjbm" placeholder="请选择" 
                            collapse-tags multiple style="width:200px;">
                             <!-- ryZjbmForUseOptions-->
                    <el-option v-for="item in  ryZjbmOptions" :key="item.value" :label="item.label"
                              :value="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发放日期">
                    <el-date-picker  v-model="searchParam.startDate"
                                    :clearable="false" style="width:110px"
                                    format="MM-dd" value-format="yyyy-MM-dd"
                                    :picker-options="dateOptions"/>
                    <slot name="range-separator">
                      <span style="width: 40px" class="el-range-separator">至</span>
                    </slot>
                    <el-date-picker  v-model="searchParam.endDate"
                                    format="MM-dd" value-format="yyyy-MM-dd"
                                    :clearable="false" style="width:110px"
                                    :picker-options="dateOptions"/>
                </el-form-item>
              </el-col>
              
              
              <el-form-item label="只检索此年度有剔除的用户" label-width="220px">
                <el-switch v-model="searchParam.onlySearchTichu" active-text="是" inactive-text="否"
                           style="width: 100px"
                           :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item label="只检索剔除金额不为0的用户" label-width="220px">
                <el-switch v-model="searchParam.onlySearchFeeNotNull" active-text="是" inactive-text="否"
                           style="width: 100px"
                           :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item>
                <el-button
                  icon="el-icon-search"
                  type="primary"
                  class="marginLeft"
                  :disabled="searchParam.rootDeptCode===''"
                  @click="getDataList()"
                  plain
                >检索
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <!--  功能按钮区，左右分布        -->
          <div style="height: 50px; border-bottom: 1px solid #b0bde2">
            <el-tooltip
              class="item"
              effect="dark"
              content="下载明细表"
              placement="top"
            >
              <el-button icon="el-icon-download" size="small" type="warning" circle
                         style="padding-right:10px"
                         @click="exportExcelForDetail"></el-button>
            </el-tooltip>
            <!-- <el-tooltip
              class="item"
              effect="dark"
              content="导入修改后明细表"
              placement="top"
            >
              <el-upload
                action='/jiangjin/tichuDetail/importExcelForDetail'
                accept=".xlsx, .xls"
                :headers="headers"
                class="upload-demo inline-block"
                :before-upload="beforeAvatarUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :data="uploadDataForDetail"
                :show-file-list="false"
                style="padding-left:10px;padding-right:10px">
                <el-button icon="el-icon-upload" size="small" type="success" circle></el-button>
              </el-upload>
            </el-tooltip> -->
            <el-tooltip
              class="item"
              effect="dark"
              content="下载汇总表"
              placement="top"
            >
              <el-button icon="el-icon-download" size="small" type="info" circle
                         @click="exportExcelForGroupBy"></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="跳转至批量处理界面"
              placement="top"
            >
              <el-button icon="el-icon-s-unfold" size="small" type="primary" circle @click="showDetailList"></el-button>
            </el-tooltip>
            <div class="pull-right"></div>
          </div>
          <!--   表格区       -->
          <el-table :data="dataList"
                    ref="tichuDetailMainTable"
                    :highlight-current-row="true"
                    v-loading="dataListLoading" stripe tooltip-effect="light"
                    :expand-row-keys="expandRowKeysForMain"
                    @expand-change="expandChangeHandle"
                    :row-key="'ryCode'"
                    class="avue-crud"
                    border>
            <el-table-column type="expand">
              <template slot-scope="parentScope">
                <div style="width: 95%;margin-left: 50px;">
                  <!-- :header-cell-style="{background:'#006666!important',color:'#fff'}" -->
                  <el-table
                    :header-cell-style="{background:'#d6ddf3!important'}"
                    :data="parentScope.row.detailDataList">
                    <!--                    <el-table-column prop="deptName" label="部门" align="center" min-width="200"></el-table-column>
                                        <el-table-column prop="ryCode" label="人员编号" align="center" min-width="80"></el-table-column>
                                        <el-table-column prop="ryZjmc" label="职级" align="center" min-width="150"></el-table-column>-->
                    <el-table-column prop="ryName" label="人员名称" align="center" min-width="60"></el-table-column>
                    <el-table-column prop="ffDate" label="发放日期" align="center" min-width="150"></el-table-column>
                    <el-table-column prop="jjxFl" label="ECC奖金项分类" align="center" min-width="150"></el-table-column>
                    <el-table-column prop="jjxMc" label="奖金项名称" align="center" min-width="150"></el-table-column>
                    <el-table-column prop="fee" label="奖金金额" align="center" min-width="120">
                      <template slot-scope="scope">
                    <span
                      @click="thisVue.addOrUpdateHandle(scope.row.id)"
                      style="color: #0e258c; cursor: pointer"
                    >{{ scope.row.fee }}</span>
                        <!--                <span v-else>{{ scope.row.fee }}</span>-->
                      </template>
                    </el-table-column>
                    <el-table-column prop="importFlag" label="是否为Excel导入" align="center" min-width="120">
                      <template slot-scope="{row}">
                        {{ row.importFlag == 1 ? '是' : '否' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="是否剔除" align="center" min-width="120">
                      <template slot-scope="{row}">
                        <el-switch v-model="row.status" active-text="是" inactive-text="否"
                                   :disabled="row.id==currentRowId"
                                   @change="changeStatusHandle(row)"
                                   active-value="1" inactive-value="0"></el-switch>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="deptName" label="部门" align="center" min-width="200"></el-table-column>
            <el-table-column prop="ryCode" label="人员编号" align="center" min-width="80"></el-table-column>
            <el-table-column prop="ryName" label="人员名称" align="center" min-width="60"></el-table-column>
            <el-table-column prop="ryZjmc" label="职级" align="center" min-width="150"></el-table-column>
            <el-table-column prop="counts" label="发放笔数" align="center" min-width="60">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="scope.row.remark"
                  placement="top"
                ><span>
                  {{ scope.row.counts }}
                </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <!--            <el-table-column prop="remark" label="说明" align="center" min-width="150"></el-table-column>-->
            <el-table-column prop="totalFee" label="奖金金额" align="center" min-width="120"/>
            <el-table-column prop="fee" label="剔除金额" align="center" min-width="120"/>
            <el-table-column prop="resultTotalFee" label="剔除后金额" align="center" min-width="120"/>
          </el-table>
          <div class="avue-crud__pagination">
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                           :current-page="pageIndex"
                           :page-sizes="pageSizes" :page-size="pageSize" :total="totalCount" background
                           layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </div>
      </div>
    </basic-container>
    <el-dialog
      :title="addOrUpdateFormMvc.title"
      :close-on-click-modal="false"
      append-to-body
      :visible.sync="addOrUpdateFormMvc.visible"
    >
      <addOrUpdateForm v-if="addOrUpdateFormMvc.visible!==undefined" ref="addOrUpdateFormRef"
                       @close="addOrUpdateFormMvc.visible=false"
                       @refreshDataList="getDataList"></addOrUpdateForm>
    </el-dialog>
    <el-dialog
      :title="detailListMvc.title"
      :close-on-click-modal="false"
      append-to-body
      fullscreen
      :beforeClose="tichuDetailListCloseHandle"
      :visible.sync="detailListMvc.visible"
    >
      <tichuDetailList v-if="detailListMvc.visible" ref="detailListMvcRef"
                       @refreshDataList="getDataList"></tichuDetailList>
    </el-dialog>
  </div>
</template>
<script>
import tichuDetailController from "@/api/jiangjin/tichuDetailController"
import tichuConfigController from "@/api/jiangjin/tichuConfigController";
import {mapGetters} from "vuex";
import {remote as remoteDict} from "@/api/admin/dict";
import {getObj as getDeptObj, getUnderDept} from "@/api/admin/dept";
import deptAvueInputTree from '@/views/admin/dept/dept-avue-input-tree'
import addOrUpdateForm from '@/views/jiangjin/tichu/tichuDetailForm'//当前列表的单体弹出框，命名便于复制
import store from "@/store";
import formatUtil from "@/api/util/formatUtil";
import request from "@/router/axios";
import {deleteBatch} from "@/api/jiangjin/jiangjinjjxxxb";
import tichuDetailList from "@/views/jiangjin/tichu/tichuDetailList";

export default {
  name: "tichuDetailIndex",
  components: {deptAvueInputTree, addOrUpdateForm, tichuDetailList},
  data() {
    return {
      thisVue: this,
      entityName: 'TichuDetail',
      //---无权限提示---------
      ymLoad: false,
      //---------------搜索条------------------
      searchAdvanced: true,
      searchheight: "0",
      importLoading: false,
      //--------------静态内容（如字典值，只需要加载一次）-------------
      jjflOptions: [],//所有的ECC奖金项列表
      jjxMcOptions: [],//当前负责部门奖金项名称列表，只取不重复的名称
      ryZjbmOptions: [],//所有职务级别，默认选中二级正和二级副，来自于字典表类型为user_zj的项
      ryZjbmForUseOptions: [],
      //--------------搜索条件--------------
      importDate: '未执行获取',
      dateOptions: {},
      searchParam: {
        years: '',
        sourceType: '2',//默认是来自系统
        ryZjbms: [],//用户选择要导入的职级，保存在tichuConfig表里
        rootDeptCode: '', //负责部门ID
        startDate: "",
        endDate: "",
        ryZjbm: [],// ['0C', '0E', '0F'],//默认只选中 二级 相关
        onlySearchTichu: 0,//是否只搜索剔除
        onlySearchFeeNotNull: 0,
      },
      //deptName: '', //负责部门名称
      bmData: [], //负责部门列表
      //-----------汇总数据表-------------
      dataInit: false,//避免搜索条件第一次加载时重复刷新
      dataList: [],//数据内容
      pageIndex: 1,
      pageSize: 10,
      pageSizes: [10, 20, 50, 100],
      totalCount: 0,
      dataListLoading: false,//加载提示控制
      expandRowKeysForMain: [],
      //-----------明细数据表------
      currentRowId: undefined,
      //-----------发放记录单体-------------
      addOrUpdateFormMvc: {
        visible: false,
        title: '',
      },
      //-----------批量删除-------------
      detailListMvc: {
        visible: false,
        title: '',
      },
      //---------------导入导出-------------
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      importVisible: false,
      importForm: {},
      uploadDataForDetail: {},
      //--------------杂项控制--------------
      tichuConfigId: undefined,
      ryZjbmsSelectAutoDropdown: false,
      ryZjbmsSelectDisabled: false,
      ryZjbmsOldValue: ""
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    ryZjbmsIfChange() {
      if (!this.searchParam.ryZjbms || !this.searchParam.ryZjbms.length) {
        return false
      }
      return this.searchParam.ryZjbms.sort().join(",") != this.ryZjbmsOldValue
    }
  },
  created() {
    this.searchParam.years = new Date().getFullYear() + ""
    this.searchParam.startDate = this.searchParam.years + "-01-01"
    this.searchParam.endDate = this.searchParam.years + "-12-31"
    remoteDict("jingjinFenLei").then(response => {
      this.jjflOptions = response.data.data
    })
    remoteDict("user_zj").then(response => {
      this.ryZjbmOptions = response.data.data
    })
    this.initRootDept();
    this.initJjxMcOptions()
  },
  /*mounted() {

  },*/
  methods: {
    searchAdvancedChangeHandle() {
      this.searchAdvanced = !this.searchAdvanced;
      if (this.searchAdvanced) {
        this.searchheight = "50";
      }
    },
    //获取当前系统的根部门节点
    initRootDept() {
      getDeptObj(1).then(({data}) => {
        if (data.data != null) {
          this.bmData = [data.data]
          this.ymLoad = false;
          this.searchParam.rootDeptCode = data.data.deptCode;
          //this.deptName = data.data[0].name;
          this.loadTichuConfig()
          this.initSearchDeptTree()
          this.getDataList();
        } else {
          this.$alert("找不到deptId为1的根部门节点");
        }
      }).catch(err => {
        this.$alert("找不到deptId为1的根部门节点");
      });
    },
    initRyZjbmForUseOptions() {
      this.ryZjbmForUseOptions = []
      let _this = this
      this.ryZjbmOptions.forEach(item => {
        if (_this.ryZjbmsOldValue.indexOf(item.value) !== -1) {
          _this.ryZjbmForUseOptions.push({value: item.value, label: item.label})
         
        }
      })
    },
    initJjxMcOptions() {
      tichuDetailController.returnAllJjxMc(this.searchParam.years).then(({data}) => {
        this.jjxMcOptions = data.data.split(",")
      })
    },
    //------------固定条件及搜索区--------------
    //切换用户管理的部门,联动重置搜索条件中的部门树根节点
    deptCodeChangeHandle() {
      this.initSearchDeptTree()
      if (this.dataInit) {
        this.getDataList()
      }
    },
    yearsChangeHandle() {
      this.searchParam.startDate = this.searchParam.years + "-01-01"
      this.searchParam.endDate = this.searchParam.years + "-12-31"
      this.loadTichuConfig()
      if (this.dataInit) {
        this.getDataList()
      }
      this.initJjxMcOptions()
    },
    //数据源切换
    sourceTypeChangeHandle() {
      this.loadTichuConfig()
      this.searchParam.jjxMc = ''
      if (this.dataInit) {
        this.getDataList()
      }
    },
    //根据用户选择年份、来源，加载导入职级和最后导入日期
    loadTichuConfig() {
      this.$message.closeAll()
      if (!this.searchParam.rootDeptCode) {
        this.$message.error("无法获取到根部门节点")
        return
      }
      tichuConfigController.initEnt(this.searchParam.years, this.searchParam.rootDeptCode, this.searchParam.sourceType).then(({data}) => {
        let result = data.data
        this.tichuConfigId = result["entity"]["id"]
        if (result["ifNew"]) {
          this.$alert("自动完成初始化，默认此年度操作领导职级是二级");
          this.ryZjbmsSelectAutoDropdown = true
          this.$refs.ryZjbmsSelectRef.focus()
        }

        let _this = this
        this.dateOptions = {
          disabledDate(time) {//控制日期类型的选取范围，下面条件为true的不允许选择
            return time.getTime() < new Date(_this.searchParam.years + "-01-01") || time.getTime() > new Date(_this.searchParam.years + "-12-31")
          }
        }
        
        //this.searchParam.ryZjbms = result["entity"]["ryZjbms"].split(",")
        this.ryZjbmsOldValue = result["entity"]["ryZjbms"]
        this.initRyZjbmForUseOptions()
        if (this.searchParam.sourceType == 1) {
          this.importDate = result["entity"]["importDate1"] ? result["entity"]["importDate1"] : '未执行获取'
        } else {
          this.importDate = result["entity"]["importDate2"] ? result["entity"]["importDate2"] : '未执行获取'
        }
      })
    },
    //用户选择的导入职级发生变化时，修改config表，用户体验不好，暂不使用此方式
    ryZjbmsChangeHandleWithAutoSave() {
      console.log("ryZjbmsChangeHandle")
      let a = this.searchParam.ryZjbms.sort()
      //无法捕捉用户完整修改这个操作，为了避免遗漏只能修改一次，改一次
      this.ryZjbmsSelectAutoDropdown = false
      this.$refs.ryZjbmsSelectRef.blur()
      this.ryZjbmsSelectDisabled = true
    },
    ryZjbmsUpdateHandle() {
      if (this.searchParam.ryZjbms.length === 0) {
        this.$alert("操作职级必须至少选择一个！")
        return
      }
      this.ryZjbmsSelectDisabled = true
      tichuConfigController.putObj({id: this.tichuConfigId, ryZjbms: this.searchParam.ryZjbms.sort().join(",")})
        .then(({data}) => {
          this.searchParam.ryZjbms = data.data["ryZjbms"].split(",")
          this.ryZjbmsOldValue = data.data["ryZjbms"]
          this.initRyZjbmForUseOptions()
          this.ryZjbmsSelectDisabled = false
        }).catch(_ => {
        this.ryZjbmsSelectDisabled = false
      })
    },
    //搜索条件的组织机构是树形结构，当管理员负责多个部门时，每次切换负责部门，搜索条件中的部门树根节点也随之切换
    initSearchDeptTree() {
      for (let i = 0; i < this.bmData.length; i++) {
        if (this.bmData[i].deptCode == this.searchParam.rootDeptCode) {
          this.$refs.searchDeptTree.init(this.bmData[i].deptId)
          break
        }
      }
    },
    returnDeptCodeFromAvueInputTree(val) {
      this.searchParam.deptCode = val
    },
    //从ECC接口或系统表中加载数据
    importDataFromInterface() {
      if (this.searchParam.sourceType == 1) {
        this.$alert('尚未实现ECC获取数据接口')
        return
      }
      this.importLoading = true
      tichuDetailController.importDataFromInterface(this.searchParam.years, this.searchParam.sourceType, this.searchParam.rootDeptCode)
        .then(res => {
          this.importLoading = false
          this.$message.closeAll()
          this.$message.success(res.data.msg)
          this.loadTichuConfig()
          this.getDataList()
        }).catch(res => {
        this.importLoading = false
      })
    },
    //------------数据表格---------------
    // 获取数据
    getDataList() {

      /*if (this.searchParam.startDate > this.searchParam.endDate) {
        this.$alert("起始日期必须小于结束日期")
        return
      }
      let params = formatUtil.deepCopyObjNotBlankProp(this.searchParam)
      params[this.entityName + '_EQS_years'] = this.searchParam.years
      params[this.entityName + '_EQS_sourceType'] = this.searchParam.sourceType
      if (this.searchParam.ryName) {
        params[this.entityName + '_LIKERIGHTS_ryName'] = this.searchParam.ryName
      }
      if (this.searchParam.ryCode) {
        params[this.entityName + '_LIKERIGHTS_ryCode'] = this.searchParam.ryCode
      }
      //工作单位特殊实现
      if (this.searchParam.deptCode) {
        params["underDeptCode"] = this.searchParam.deptCode
      }
      //ECC奖金分类
      if (this.searchParam.jjxFl) {
        params[this.entityName + '_EQS_jjxFl'] = this.searchParam.jjxFl
      }
      if (this.searchParam.jjxMc) {
        params[this.entityName + '_EQS_jjxMc'] = this.searchParam.jjxMc
      }

      params[this.entityName + '_GES_ffDate'] = this.searchParam.startDate
      params[this.entityName + '_LES_ffDate'] = this.searchParam.endDate

      //搜索职级，为了允许用户能导入不在范围的职级，允许忽略此搜索条件
      //console.log(this.searchParam.ryZjbm)
      if (this.searchParam.ryZjbm && this.searchParam.ryZjbm.length) {
        params[this.entityName + '_INS_ryZjbm'] = this.searchParam.ryZjbm.join(",");
      }
      if (this.searchParam.onlySearchTichu) {
        params['onlySearchTichu'] = 1
      }
      if (this.searchParam.onlySearchFeeNotNull) {
        params['onlySearchFeeNotNull'] = 1
      }*/
      let params = this.returnParams()
      if (!params) {
        return
      }
      this.expandRowKeysForMain = []//设置都收起
      //params={};
      this.dataListLoading = true
      tichuDetailController.sumForResult(Object.assign({
        current: this.pageIndex,
        size: this.pageSize,
        orderByColumn: 'ryCode'
      }, params)).then(res => {
        let dl = res.data.data.records
        //detailDataList
        for (let i = 0; i < dl.length; i++) {
          dl[i]['detailDataList'] = []//必须给默认值，否则后期绑定不上
        }
        this.dataList = dl
        this.totalCount = res.data.data.total
        this.dataListLoading = false
        if (!this.dataInit) {
          this.dataInit = true
        }
      }).catch(errRes => {
        this.dataListLoading = false
      })
    },
    /**
     * 刷新指定员工编号对应的数据行
     */
    refreshRow(ryCode) {
      if (this.searchParam.startDate > this.searchParam.endDate) {
        this.$alert("起始日期必须小于结束日期")
        return
      }
      let params = formatUtil.deepCopyObjNotBlankProp(this.searchParam)
      params[this.entityName + '_EQS_years'] = this.searchParam.years
      params[this.entityName + '_EQS_sourceType'] = this.searchParam.sourceType
      params[this.entityName + '_EQS_ryCode'] = ryCode
      //ECC奖金分类
      if (this.searchParam.jjxFl) {
        params[this.entityName + '_EQS_jjxFl'] = this.searchParam.jjxFl
      }
      if (this.searchParam.jjxMc) {
        params[this.entityName + '_EQS_jjxMc'] = this.searchParam.jjxMc
      }

      params[this.entityName + '_GES_ffDate'] = this.searchParam.startDate

      params[this.entityName + '_LES_ffDate'] = this.searchParam.endDate

      //搜索职级，为了允许用户能导入不在范围的职级，允许忽略此搜索条件
      //console.log(this.searchParam.ryZjbm)
      if (this.searchParam.ryZjbm && this.searchParam.ryZjbm.length) {
        params[this.entityName + '_INS_ryZjbm'] = this.searchParam.ryZjbm.join(",");
      }
      //params={};
      this.dataListLoading = true
      tichuDetailController.sumForResultRow(Object.assign({}, params)).then(res => {
        let rowData = res.data.data
        for (let i = 0; i < this.dataList.length; i++) {
          if (this.dataList[i]['ryCode'] === ryCode) {
            //必须一个一个属性修改，直接 this.dataList[i]=rowData 不生效
            this.dataList[i]['totalFee'] = rowData['totalFee']
            this.dataList[i]['fee'] = rowData['fee']
            this.dataList[i]['resultTotalFee'] = rowData['resultTotalFee']
            //console.log(this.dataList[i])
            break
          }
        }

        this.dataListLoading = false
      }).catch(errRes => {
        this.dataListLoading = false
      })
    },
    /**
     * 当用户对某一行展开或者关闭的时候会触发该事件（展开行时，第二个参数expandedRows 回调
     * row, expandedRows
     */
    expandChangeHandle(row, expandedRows) {
      //
      let findFlag = false
      //加载数据到 row.detailDataList
      for (let i = 0; i < expandedRows.length; i++) {
        if (expandedRows[i]['ryCode'] === row['ryCode']) {
          this.getDetailDataList(row, expandedRows)
          findFlag = true
          break
        }
      }
      if (findFlag) {
        this.$refs.tichuDetailMainTable.setCurrentRow(row)
      } else {
        this.$refs.tichuDetailMainTable.setCurrentRow()
      }
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      if (id) {
        this.addOrUpdateFormMvc.title = "修改补充发放记录"
      } else {
        this.addOrUpdateFormMvc.title = "新增补充发放记录"
      }
      this.addOrUpdateFormMvc.visible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRef.init(id, false, this.searchParam.sourceType);
      })
    },
    deleteBatch() {
      let data = this.$refs.tichuDetailMainTable.selection;
      if (data.length == 0) {
        this.$message.closeAll();
        this.$message.error("请选择要删除的记录！");
        return;
      }
      let ids = [];
      let hasNoImport = false
      for (let i = 0; i < data.length; i++) {
        if (data[i]["importFlag"] != 1) {
          hasNoImport = true
          this.$refs.tichuDetailMainTable.toggleRowSelection(data[i], false)
        } else {
          ids.push(data[i].id);
        }
      }
      if (hasNoImport) {
        this.$message.closeAll()
        this.$message.warning("自动从选中的行中去掉了非导入行")
      }
      let idsStr = ids.join(",");
      this.$confirm("是否要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return tichuDetailController.deleteBatch(idsStr);
        })
        .then((data) => {
          this.$message.closeAll();
          this.$message.success("删除成功");
          this.getDataList();
        });
    },
    nShowIndex(row, column, cellValue, index) {
      return index + 1 + this.pageSize * (this.pageIndex - 1);
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    //--------------------导入导出------------
    /**
     * 文件上传前
     */
    beforeAvatarUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    /**
     * 文件上传成功到pigx的统计文件管理后转发
     */
    handleUploadSuccess(response, file, fileList) {
      this.loading.close()
      this.getDataList();
      this.$message.closeAll()
      if (response.data) {//如果解析数据中由特殊情况，向前台返回1，有错误数据返回2
        if (response.data == 2) {
          this.$message.error(response.msg)
        } else {
          this.$message.warning(response.msg)
        }
      } else {
        this.$message.success(response.msg)
      }
    },
    handleUploadError(response, file, fileList) {
      this.loading.close()
      this.$message.error('上传出错：' + response.message)
    },
    /**
     * 从静态地址汇总下载模板静态文件，复杂情况不能使用这种方式
     */
    exportTemplate() {
      window.location.href = '../../static/已发奖金补充导入模板.xlsx'
    },
    returnParams() {
      if (this.searchParam.startDate > this.searchParam.endDate) {
        this.$alert("起始日期必须小于结束日期")
        return null
      }
      let params = formatUtil.deepCopyObjNotBlankProp(this.searchParam)
      params[this.entityName + '_EQS_years'] = this.searchParam.years
      params[this.entityName + '_EQS_sourceType'] = this.searchParam.sourceType
      if (this.searchParam.ryName) {
        params[this.entityName + '_LIKERIGHTS_ryName'] = this.searchParam.ryName
      }
      if (this.searchParam.ryCode) {
        params[this.entityName + '_LIKERIGHTS_ryCode'] = this.searchParam.ryCode
      }
      //工作单位特殊实现
      if (this.searchParam.deptCode) {
        params["underDeptCode"] = this.searchParam.deptCode
      }
      //ECC奖金分类
      if (this.searchParam.jjxFl) {
        params[this.entityName + '_EQS_jjxFl'] = this.searchParam.jjxFl
      }
      if (this.searchParam.jjxMc) {
        params[this.entityName + '_EQS_jjxMc'] = this.searchParam.jjxMc
      }

      params[this.entityName + '_GES_ffDate'] = this.searchParam.startDate
      params[this.entityName + '_LES_ffDate'] = this.searchParam.endDate

      //搜索职级，为了允许用户能导入不在范围的职级，允许忽略此搜索条件
      //console.log(this.searchParam.ryZjbm)
      if (this.searchParam.ryZjbm && this.searchParam.ryZjbm.length) {
        params[this.entityName + '_INS_ryZjbm'] = this.searchParam.ryZjbm.join(",");
      }
      if (this.searchParam.onlySearchTichu) {
        params['onlySearchTichu'] = 1
      }
      if (this.searchParam.onlySearchFeeNotNull) {
        params['onlySearchFeeNotNull'] = 1
      }
      return params;
    },
    exportExcelForDetail() {
      let params = this.returnParams()
      if (!params) {
        return
      }
      tichuDetailController.exportExcelForVue(this, "exportExcelForDetail", params, {})
    },
    exportExcelForGroupBy() {
      let params = this.returnParams()
      if (params) {
        tichuDetailController.exportExcelForVue(this, "exportExcelForGroupBy", params, {})
      }
    },
    //-------------------详细表处理-------------------
    changeStatusHandle(row) {
      this.currentRowId = row.id
      tichuDetailController.putObj(row).then(({data}) => {
        row = data.data
        this.currentRowId = undefined
        //联动更新细节表所在的行，如果执行 this.getDataList() 会导致细节表收起
        this.refreshRow(row['ryCode'])
        //this.$message.success('修改成功')
      });
    },
    getDetailDataList(row, expandedRows) {
      console.log(row, "getDetailDataList")
      if (this.searchParam.startDate > this.searchParam.endDate) {
        this.$alert("起始日期必须小于结束日期")
        return
      }
      let params = formatUtil.deepCopyObjNotBlankProp(this.searchParam)
      params[this.entityName + '_EQS_years'] = this.searchParam.years
      params[this.entityName + '_EQS_sourceType'] = this.searchParam.sourceType
      //关联当前行的人员
      params[this.entityName + '_EQS_ryCode'] = row.ryCode
      //ECC奖金分类
      if (this.searchParam.jjxFl) {
        params[this.entityName + '_EQS_jjxFl'] = this.searchParam.jjxFl
      }
      if (this.searchParam.jjxMc) {
        params[this.entityName + '_EQS_jjxMc'] = this.searchParam.jjxMc
      }

      params[this.entityName + '_GES_ffDate'] = this.searchParam.startDate
      params[this.entityName + '_LES_ffDate'] = this.searchParam.endDate
      //搜索职级，为了允许用户能导入不在范围的职级，允许忽略此搜索条件
      //console.log(this.searchParam.ryZjbm)
      if (this.searchParam.ryZjbm && this.searchParam.ryZjbm.length) {
        params[this.entityName + '_INS_ryZjbm'] = this.searchParam.ryZjbm.join(",");
      }
      //params={};
      this.dataListLoading = true
      tichuDetailController.fetchPage(Object.assign({
        size: 999,//为了避免误会不分页
        orderByColumn: 'deptCode,ryCode,ffDate,jjxFl,jjxMc'
      }, params)).then(({data}) => {
        row.detailDataList = data.data.records
        row.totalCount = data.data.total
        this.dataListLoading = false
        if (!this.dataInit) {
          this.dataInit = true
        }
      }).catch(errRes => {
        this.dataListLoading = false
      })
    },
    showDetailList() {
      this.detailListMvc.title = "批量剔除"
      this.detailListMvc.visible = true
      this.$nextTick(_ => {
        this.$refs.detailListMvcRef.init(this.searchParam.years, this.searchParam.sourceType, this.searchParam.rootDeptCode)
      })
    },
    tichuDetailListCloseHandle() {
      this.detailListMvc.visible = false
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
/*缩短提示文字行间距*/
.colForm /deep/ .el-form-item__label {
  line-height: 20px !important;
}

/*避免换行不正确*/
.colForm /deep/ .el-row {
  display: flex;
  flex-wrap: wrap;
}

/* 设置分割线margin-top为0px*/
.el-divider--horizontal {
  margin: 0px 0px 20px 0px;
}

/*选中行颜色*/
.zhiBiao /deep/ .el-table__body tr.current-row td, .el-table__body tr.current-row > td {
  background-color: #ffffb3 !important;
}
</style>
